package com.advertisementsystem.Servie.Impl;

import com.advertisementsystem.Dto.LoginUser;
import com.advertisementsystem.Exception.BusinessException;
import com.advertisementsystem.Mapper.PermissionMapper;
import com.advertisementsystem.Mapper.RoleMapper;
import com.advertisementsystem.Mapper.UserMapper;
import com.advertisementsystem.entity.Permission;
import com.advertisementsystem.entity.Role;
import com.advertisementsystem.entity.User;
import com.advertisementsystem.utils.RedisCache;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RedisCache redisCache; // Redis缓存工具类

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("用户名: {}", username);
        // // 1. 查询用户信息
        // LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //
        // queryWrapper.eq(User::getUsername, username);

        User user = userMapper.selectByUsernameDirect(username);

        // System.out.println("user: " + user);

        log.info("用户{}", user);

        if (Objects.isNull(user)) {
            throw new BusinessException("用户名不存在");
        }

        // 2. 尝试从缓存获取权限信息
        String permissionKey = "permission:user:" + user.getId();

        List<String> permissions = redisCache.getCacheObject(permissionKey);

        log.info("permissions: {}", permissions);
        if (permissions == null) {
            // 3. 缓存未命中，从数据库查询
            List<Role> roles = roleMapper.selectRolesByUserId(user.getId());
            List<Permission> permissionList = permissionMapper.selectPermissionsByUserId(user.getId());

            permissions = new ArrayList<>();

            // 添加角色标识
            List<String> finalPermissions1 = permissions;
            roles.forEach(role -> {
                finalPermissions1.add("ROLE_" + role.getCode().toUpperCase());
            });

            // 添加具体权限标识
            List<String> finalPermissions = permissions;
            permissionList.forEach(permission -> {
                if (StringUtils.hasText(permission.getCode())) {
                    finalPermissions.add(permission.getCode());
                }
            });

            // 4. 将权限信息存入缓存
            redisCache.setCacheObject(permissionKey, permissions, 24, TimeUnit.HOURS);
        }
        return new LoginUser(user, permissions);
    }
}